package com.demo.task;

import com.demo.core.ActionContext;
import com.demo.po.ApplicationPo;
import com.demo.po.LogPo;
import com.demo.service.IApplicationService;
import com.demo.service.ILogService;
import com.demo.service.IServerService;
import com.demo.service.common.BizCache;
import com.demo.utils.ShellUtils;
import com.jcraft.jsch.Session;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@DisallowConcurrentExecution
@Service
public class LoadLogTask extends QuartzJobBean {

    protected Logger log = LoggerFactory.getLogger(LoadLogTask.class);

    @Autowired
    private IServerService serverService;

    @Autowired
    private IApplicationService applicationService;

    @Autowired
    private ILogService logService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.debug("开始执行错误日志加载任务...");

        String now = BizCache.getInstance().getNow();
        String tenmi = now.substring(0, 15);

        // 只找最近10分钟的错误
        Pattern errorspattern = Pattern.compile("\\[" + tenmi + "\\d{1}:\\d{2}:\\d{3}\\] \\[ERROR\\][\\s\\S]*");

        List<ApplicationPo> applications = applicationService.findAllApplications(new ApplicationPo());
        for (ApplicationPo application : applications) {
            Session session = ActionContext.getSession(application.getServerid());
            if (session == null) {
                log.error("server " + application.getHost() + " is not connected.");
                continue;
            }
            List<String> logs = ShellUtils.execCmd(session, "cat " + application.getDeveloppath() + "/logs/error.log");
            if (logs == null) {
                log.error("application " + application.getApplicationname() + " has not logs.");
                continue;
            }
            boolean haserror = false;
            List<String> errors = new ArrayList();
            String errortime = "";
            for (String line : logs) {
                if (errorspattern.matcher(line).matches()) {
                    if (errors.size() > 0) {
                        LogPo logPo = new LogPo(application.getServerid(), application.getApplicationid());
                        logPo.setDetail(String.join("\n", errors));
                        logPo.setLogtime(errortime);
                        logService.addLog(logPo);
                        haserror = false;
                        errors = new ArrayList();
                    }
                    haserror = true;
                    errortime = line.substring(0, line.indexOf("]") + 1);
                }
                if (haserror)
                    errors.add(line);
            }
            if (errors.size() > 0) {
                LogPo logPo = new LogPo(application.getServerid(), application.getApplicationid());
                logPo.setDetail(String.join("\n", errors));
                logPo.setLogtime(errortime);
                logService.addLog(logPo);
            }
        }
        log.debug("日志加载完成");
    }
}
